package com.zt.english.utils

import okhttp3.internal.and
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * 有道文本翻译工具类
 */
object TranslateUtil {
    private val YOUDAO_APPID = "5ecc16e89f27fe79"
    private val YOUDAO_APP_KEY = "DvjuJCOUbpzfdlnjSsopJEW033pwXBDE"

    /**
     * 道友文本翻译参数封装
     */
    fun parameters(q :String): HashMap<String,String>{
        val crurtime = (System.currentTimeMillis()/1000).toString()
        val salt = System.currentTimeMillis().toString()
        val map = HashMap<String,String>()
        map.put("q",q)
        map.put("from","en")
        map.put("to","zh-CHS")
        map.put("appKey",YOUDAO_APPID)
        map.put("salt",salt)
        map.put("sign",sign(q,salt,crurtime))
        map.put("signType","v3")
        map.put("curtime",crurtime)
        map.put("strict","false")
        return map
    }
    /**
     sha256(应用ID+input+salt+curtime+应用密钥)；
    其中，input的计算方式为：input=q前10个字符 + q长度 + q后10个字符（当q长度大于20）或 input=q字符串（当q长度小于等于20）；
     */
    private fun sign(q: String, salt: String, crurtime: String):String{
        val sign = YOUDAO_APPID+ truncate(q)+salt+crurtime+YOUDAO_APP_KEY
        return JavaUtils.getDigest(sign)
    }

    private fun truncate(q: String): String{
        val len = q.length
        return if (len <= 20) q else q.substring(0, 10) + len + q.substring(len - 10, len)
    }

    /**
     * 生成加密字段
     */
    private fun getDigest(string: String?): String? {
        if (string == null) return null
        val hexDigits = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
        val btInput = string.toByteArray(StandardCharsets.UTF_8)
        return try {
            val mdInst = MessageDigest.getInstance("SHA-256")
            mdInst.update(btInput)
            val md = mdInst.digest()
            val j = md.size
            val str = CharArray(j * 2)
            var k = 0
            for (byte0 in md) {
//                str[k++] = hexDigits[byte0 ushr 4 and 0xf]
                str[k++] = hexDigits[byte0 and 0xf]
            }
            String(str)
        } catch (e: NoSuchAlgorithmException) {
            null
        }
    }
}